import userApi from '@/api/user'
import articleApi from "@/api/article"
import analysisApi from "@/api/analysis"
import { saveItem, getItem, delItem } from '@/utils/storage'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  userId: '',
  userType:'',
  name: '',
  mobile: '',
  email: '',
  avatar: 'http://wmhb.wm-mis.com/man_head.jpg',
  introduction: '',
  check_num:0,
  orgnizations: [],
  privileges: [],
  reportLists:[],
  roles: [],
  relateSys:null
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERID: (state, uid) => {
    state.userId = uid
  },
  SET_USERTYPE:(state, type)=>{
    state.userType = type
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_MOBILE: (state, mobile) => {
    state.mobile = mobile
  },
  SET_EMAIL: (state, email) => {
    state.email = email
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PRIVILEGES: (state, privileges) => {
    state.privileges = privileges
  },
  SET_ORGNIZATIONS: (state, orgs) => {
    state.orgnizations = orgs
  },
  SET_CHECKNUM: (state,num)=>{
    state.check_num = num
  },
  SET_REPORTLISTS:(state,reports)=>{
    state.reportLists = reports
  },
  SET_RELATESYSTEM:(state, sys)=>{
    state.relateSys = sys
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { mobile, password } = userInfo
    return new Promise((resolve, reject) => {
      userApi.login({ mobile: mobile.trim(), password: password }).then(response => {
        const { data } = response
        const orgs = data.user.orgnizations
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve(orgs)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      userApi.getInfo(state.token).then(response => {
        const { data } = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { user, privileges } = data

        // roles must be a non-empty array
        if (!user.roles || user.roles.length <= 0) {
          reject('getInfo: roles must be a non-null array!')
        }
        commit('SET_USERID', user.id)
        commit('SET_USERTYPE', user.type)
        commit('SET_ROLES', user.roles)
        commit('SET_NAME', user.name)
        commit('SET_MOBILE', user.mobile)
        commit('SET_EMAIL', user.email)
        commit('SET_PRIVILEGES', privileges)
        commit('SET_RELATESYSTEM',data.switch)
        commit('SET_ORGNIZATIONS', user.orgnizations)
        const orgnizeList = JSON.stringify(user.orgnizations)
        saveItem('orgnizes', orgnizeList)
        dispatch('getNotify')
        dispatch('analysisTbList')
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  getNotify({commit, state}){
    return new Promise((resolve,reject)=> {
      articleApi.approvalNotify().then(response=>{
        const { data } = response
        commit('SET_CHECKNUM', data.check_num)
        resolve(data)
      }).catch(err=>{
        reject(err)
      })
    })
  },
  analysisTbList({commit, state}){
    return new Promise((resolve,reject)=> {
      analysisApi.analysisTableList().then(response=>{
        const { data } = response
        commit('SET_REPORTLISTS', data)
        const reportList = JSON.stringify(data)
        saveItem('reports', reportList)
        resolve(data)
      }).catch(err=>{
        reject(err)
      })
    })
  },
  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      userApi.logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ORGNIZATIONS', [])
        commit('SET_ROLES', [])
        removeToken()
        delItem('orgnizes')
        delItem('reports')
        // resetRouter()
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  async ownedOrgnizes({ commit, state },fac_type=2) {
    let mainOrgnize = {
      id:1,
      name:'伟明环保股份有限公司',
      title:'伟明环保股份有限公司',
      type:'ancestor',
      disabled:true,
      children:[]
    }
    let orgnizeList = Object.assign([],state.orgnizations)
    orgnizeList.forEach(org=>org.children=[])
    if (fac_type==1)
      orgnizeList = orgnizeList.filter(org=>org.is_food===1)
    else if (fac_type==3)
      orgnizeList = orgnizeList.filter(org=>org.is_food===3)
    else if (fac_type==2)
      orgnizeList = orgnizeList.filter(org=>[1,2].indexOf(org.is_food)>-1)
    mainOrgnize.children = orgnizeList
    return new Promise(resolve => {
      resolve([mainOrgnize])
    })
  },
  async refreshToken({commit}){
    return new Promise((resolve, reject) => {
      userApi.refreshToken().then(res=>{
        const access_token = res.data.token
        commit('SET_TOKEN', access_token)
        setToken(access_token)
        resolve(access_token)
      }).catch(err=>{
        reject(err)
      })
    })
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ORGNIZATIONS', [])
      commit('SET_ROLES', [])
      removeToken()
      delItem('orgnizes')
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
